import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Form, FormProps, Modal, Select, TreeSelect } from 'antd';
import { DataNode } from 'antd/lib/tree';

import { store } from '@/store';

import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import {
  orgUserInfoSetDept,
  orgUserInfoSetMainDept
} from '@/services/base/yonghuguanlixitongyonghujiekou';

import { BizObject } from '.';

export type EditDeptRef = {
  open: (arg: { rowData: BizObject; onSuccess?: () => void }) => void;
};

export type EditDeptProps = {};

const EditDept: React.ForwardRefRenderFunction<EditDeptRef, EditDeptProps> = ({ ...rest }, ref) => {
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditDeptRef['open']>[0]>();
  const treeDict = useRef<Record<number, DataNode>>({});
  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });
  const submit = useRequest(
    async ({ deptIds, deptId }: { deptIds: number[]; deptId: number }) => {
      await orgUserInfoSetDept({
        userId: args?.rowData.id as number,
        deptIds: deptIds as number[]
      });
      await orgUserInfoSetMainDept({
        userId: args?.rowData.id as number,
        deptId: deptId as number
      });
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
        console.log(arg.rowData.mainDeptInfos?.id);
        form.setFieldsValue({
          deptIds: arg.rowData.deptInfos?.map((item) => item.id),
          deptId: arg.rowData.mainDeptInfos?.id
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async ({ deptId, deptIds }) => {
    await submit.run({
      deptIds: deptIds as number[],
      deptId: deptId as number
    });

    args?.onSuccess?.();
    setOpen(false);
    store.app?.message.success('操作成功');
  };

  const onClose = () => {
    if (submit.loading) {
      store.app?.message.error('请等待操作完成');

      return;
    }

    form.resetFields();
    setOpen(false);
  };

  return (
    <Modal
      title="修改部门"
      width={424}
      {...rest}
      okButtonProps={{
        disabled: submit.loading,
        loading: submit.loading
      }}
      cancelButtonProps={{
        disabled: submit.loading
      }}
      open={open}
      onCancel={onClose}
      onOk={() => {
        form.submit();
      }}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <Form.Item name="deptIds" label="部门">
          <TreeSelect
            treeData={tree.data}
            treeNodeFilterProp="title"
            showSearch
            placeholder="请选择部门"
            allowClear
            multiple
            onChange={() => {
              form.resetFields(['deptId']);
            }}
          />
        </Form.Item>
        <Form.Item noStyle shouldUpdate>
          {({ getFieldsValue }) => {
            const { deptIds } = getFieldsValue();

            return (
              <Form.Item name="deptId" label="主部门">
                <Select
                  placeholder="请选择主部门"
                  options={(deptIds as number[])?.map((id) => {
                    const node = treeDict.current[id];

                    return {
                      label: node?.title ?? id,
                      value: id
                    };
                  })}
                />
              </Form.Item>
            );
          }}
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default forwardRef(EditDept);
